package com.yehun.admin.socket;

import com.yehun.shiro.ShiroUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

public class UserImSocket extends TextWebSocketHandler {

    private final static Logger logger = LoggerFactory.getLogger(UserImSocket.class);

    private WebSocketSession session;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
        ShiroUser currentUser = getCurrentUser();
        if (currentUser == null) {
            logger.info("currentUser is null!");
        } else {
            logger.info("userId: {}", currentUser.getName());
        }
        logger.info("有新连接加入!");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws IOException {
        this.session = session;
        if (this.session.isOpen()) {
            this.session.close();
        }
        logger.info("有一连接关闭!");
    }


    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        this.session = session;
        logger.info(String.format("来自客户端的消息:%s", message.getPayload()));
        ShiroUser currentUser = getCurrentUser();
        if (currentUser == null) {
            logger.info("currentUser is null!");
        } else {
            logger.info("userId: {}", currentUser.getName());
        }
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        this.session = session;
        if (this.session.isOpen()) {
            this.session.close();
        }
        logger.info("连接出错");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }



    private ShiroUser getCurrentUser() {
        Object object = this.session.getAttributes().get("currentUser");
        if (object != null) {
            return (ShiroUser) object;
        }
        return null;
    }
}
